<!-- src/components/Vditor.vue -->
<template>
	<div ref="vditorRef" class="vditor-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import Vditor from 'vditor';
import 'vditor/dist/index.css';

const props = defineProps<{
	modelValue?: string | null | undefined;
	height?: number;
	placeholder?: string;
}>();

const emit = defineEmits<{
	(e: 'update:modelValue', value: string | undefined): void;
}>();

const vditorRef = ref<HTMLElement | null>(null);
let vditor: Vditor | null = null;

// 初始化Vditor
const initVditor = () => {
	if (vditorRef.value) {
		const element = vditorRef.value as HTMLElement;
		vditor = new Vditor(element, {
			height: props.height || 400,
			placeholder: props.placeholder || '',
			toolbarConfig: {
				pin: true,
			},
			cache: {
				enable: false,
			},
			after: () => {
				if (props.modelValue) {
					vditor?.setValue(props.modelValue);
				}
			},
			input: (value: string) => {
				emit('update:modelValue', value);
			},
			focus: (value: string) => {
				emit('update:modelValue', value);
			}
		});
	}
};

// 监听值变化
watch(() => props.modelValue, (newValue) => {
	if (!newValue)
		newValue = '';
	if (vditor && newValue !== vditor.getValue()) {
		vditor.setValue(newValue || '');
	}
});

// 组件挂载时初始化
onMounted(() => {
	nextTick(() => {
		initVditor();
	});
});

// 组件销毁时清理
onUnmounted(() => {
	if (vditor) {
		vditor.destroy();
	}
});

// 提供获取值的方法
defineExpose({
	getVditor: () => vditor
});
</script>

<style scoped>
.vditor-container {
	border: 1px solid #d9d9d9;
	border-radius: 4px;
}
</style>
